package com.dimbottom.controller;

import com.dimbottom.entity.rest.Rest;
import com.dimbottom.entity.rest.RestBody;
import com.dimbottom.entity.Student;
import com.dimbottom.service.StudentService;
import com.dimbottom.entity.rest.Code;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@Api(value = "学号管理", tags = "学号管理")
@RestController
public class StudentController {

    StudentService studentService;

    @ApiOperation(value = "学号列表", notes = "不对外开放使用", httpMethod = "GET")
    @GetMapping("/student/list")
    public Rest<List<Student>> list() {
        List<Student> list = studentService.list();
        return RestBody.okData(list);
    }

    @ApiOperation(value = "添加学号", httpMethod = "POST")
    @ApiResponse(code = 200, message = "", response = RestBody.class)
    @PostMapping("/student")
    public Rest<Void> insert(@RequestBody @Valid Student student) {
        try {
            student.setLevel(student.getLevel() == 1 ? 1 : 0);
            studentService.save(student);
            return RestBody.ok();
        } catch (Exception e) {
            return RestBody.failure(Code.AlreadyExisted, "student code already exists!");
        }
    }

    @ApiOperation(value = "删除学号", httpMethod = "DELETE")
    @DeleteMapping("/student")
    public Rest<Void> delete(@RequestBody @Valid Student student) {
        Student check = studentService.getById(student.getStudentCode());
        if (check == null)
            return RestBody.failure(Code.AlreadyDeleted, "student code already delete!");
        if (check.getLevel() == 0) {
            studentService.removeById(student.getStudentCode());
            return RestBody.ok();
        }
        return RestBody.failure(Code.Unauthorized, "unable to delete, please contact administrator");
    }

    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }
}
